package com.club.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.club.common.exception.BusinessException;
import com.club.entity.Club;
import com.club.mapper.ClubMapper;
import com.club.service.ClubService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 社团服务实现类
 */
@Service
public class ClubServiceImpl extends ServiceImpl<ClubMapper, Club> implements ClubService {

    @Override
    @Transactional
    public boolean createClub(Club club) {
        // 设置默认值
        club.setStatus(0);
        club.setCreateTime(LocalDateTime.now());
        club.setUpdateTime(LocalDateTime.now());
        
        // 保存俱乐部信息
        boolean saved = this.save(club);
        if (!saved) {
            throw new BusinessException("创建社团失败");
        }
        
        return true;
    }

    @Override
    @Transactional
    public boolean updateClub(Club club) {
        // 检查俱乐部是否存在
        Club existingClub = this.getById(club.getId());
        if (existingClub == null) {
            throw new BusinessException("社团不存在");
        }
        
        // 更新时间
        club.setUpdateTime(LocalDateTime.now());
        
        return this.updateById(club);
    }

    @Override
    @Transactional
    public boolean deleteClub(Long clubId) {
        // 检查俱乐部是否存在
        Club club = this.getById(clubId);
        if (club == null) {
            throw new BusinessException("社团不存在");
        }
        
        return this.removeById(clubId);
    }

    @Override
    public List<Club> getClubsByLeaderId(Long leaderId) {
        return this.getBaseMapper().selectByLeaderId(leaderId);
    }

    @Override
    public List<Club> getClubsByUserId(Long userId) {
        return this.getBaseMapper().selectByUserId(userId);
    }

    @Override
    public List<Club> getAllClubs(Integer status) {
        if (status != null) {
            return this.lambdaQuery().eq(Club::getStatus, status).list();
        }
        return this.list();
    }
}